package com.gin.kotlin.no_gay_alliance.fragment.main

import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.activity.MainActivity
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity.Companion.attachTabLayout
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.databinding.FragmentMainTabBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

/**
 * [com.gin.kotlin.no_gay_alliance.activity.MainActivity] 使用的FragmentState公共模板
 * @property tabLayoutMediator TabLayoutMediator
 * @property fragmentStateContainers List<FragmentStateContainer>
 */
abstract class AbstractMainTabFragment : AbstractBindingFragment<FragmentMainTabBinding>(), TabLayoutMediator.TabConfigurationStrategy {
    private lateinit var tabLayoutMediator: TabLayoutMediator
    private lateinit var fragmentStateContainers: List<FragmentStateContainer>

    override fun onCreateView() {
        val b = this.b ?: return
        this.fragmentStateContainers = obtainFragmentStateContainers()
        // 为ViewPager2设置适配器
        b.viewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = fragmentStateContainers.size
            override fun createFragment(position: Int) = FragmentStateContainer.newInstance(fragmentStateContainers, position)
        }
        this.tabLayoutMediator = attachTabLayout(b.tabLayout, b.viewPager2, this)

        onCreateView2()
    }

    override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
        tab.text = fragmentStateContainers[position].title
        fragmentStateContainers[position].icon?.also { tab.setIcon(it) }
    }

    abstract fun obtainFragmentStateContainers(): List<FragmentStateContainer>

    abstract fun onCreateView2()

    override fun onResume() {
        super.onResume()

        // 显示时调用activity
        (requireActivity() as? MainActivity)?.onFragmentVisible(this)
    }
}
